package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.exception.NoNullException;
import com.sky.result.Result;
import com.sky.utils.AliOssUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@Api(tags = "公共接口")
@Slf4j
@RequestMapping("/admin/common/upload")
public class CommonController {

    @Autowired
    private AliOssUtils aliOssUtils;

    @PostMapping
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        //截取最後一個.的後面的字串
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        //UUID生成随机字符串+文件后缀作爲新的文件名，防止文件名重复
        String uuid = UUID.randomUUID().toString();
        String newFilename = uuid + "." + suffix;
        String filename = null;
        try {
            filename = aliOssUtils.upload(file.getBytes(), newFilename);
        } catch (IOException e) {
            throw new NoNullException(MessageConstant.FILE_UPLOAD_ERROR);
        }
        return Result.success(filename);
    }
}
